package utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import domain.Page;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

public class CrawlerUtils {
    //UUID生成器
    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }

    public static String getGoodsId(String url) {
        int start = url.lastIndexOf("/");
        int end = url.lastIndexOf(".");
        return url.substring(start + 1, end);
    }

    public static String getDomain(String url) throws MalformedURLException {
        URL domain = new URL(url);
        String domainName = domain.getHost();
        return domainName;
    }


    public static String getHtml(String url) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpUriRequest httpget = new HttpGet(url);
        CloseableHttpResponse response = client.execute(httpget);
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }


    public static double parsePrice(String priceUrl) throws IOException {
        String priceJson = getHtml(priceUrl);
        if(priceJson.contains("error"))
            return -1;
        JSONArray jsonArray = JSON.parseArray(priceJson);
        JSONObject obj = (JSONObject) jsonArray.get(0);
        return Double.valueOf((String) obj.get("p"));
    }

    public static void getComment(Page page) throws IOException {
        String commentUrl = "https://club.jd.com/comment/productCommentSummaries.action?referenceIds="
                + page.getGoodid();
        //请求没有加时间戳貌似可以
        String content = getHtml(commentUrl);

        if(content.contains(""))
        {
            page.setComments(-1);
            page.setGoodRate(-1);
            return;
        }

        JSONObject json = (JSONObject) JSON.parse(content);
        double rate = ((BigDecimal) ((JSONObject) json.getJSONArray("CommentsCount").get(0)).get("GoodRate")).doubleValue();
        int counts = (int) (((JSONObject) json.getJSONArray("CommentsCount").get(0)).get("CommentCount"));
        page.setComments(counts);
        page.setGoodRate(rate);
    }

    //商品简介参数解析
    public static JSONObject getPara(Page page) {
        Document doc = Jsoup.parse(page.getContent());
        JSONObject info = new JSONObject();
        JSONObject intro = new JSONObject();

        Document para = Jsoup.parse(doc.select("div[class='p-parameter']").html());
        if(para.text().contains(":"))
        {
            para.getElementsMatchingOwnText("：").forEach(element -> {
                String item = element.text();
                try {
                    info.put(item.split("：")[0], item.split("：")[1]);
                }catch (ArrayIndexOutOfBoundsException e)
                {
                    info.put("null","null");
                }
            });
        }

        intro.put("商品介绍", info);
        return intro;
    }

    //商品详细参数解析
    public static JSONObject getDetail(Page page) throws IOException {
        Document doc = Jsoup.parse(page.getContent());

        JSONArray detail = new JSONArray();

        Elements paralist = doc.select("div[class='Ptable']").select("div[class='Ptable-item']");
        paralist.forEach(element -> {
            JSONObject aspectInfo = new JSONObject();
            String aspect = element.select("h3").text();

            element.getElementsByTag("h3").next().select("dl[class='clearfix']").forEach(child -> {
                String key = child.select("dt").text();
                //去掉tip，去除多余标签。
                String value = child.children().not("dd[class='Ptable-tips']").select("dd").text();

//               String value = child.select("dd").last().text();
                aspectInfo.put(key, value);
            });
            JSONObject item = new JSONObject();
            item.put(aspect, aspectInfo);
            detail.add(item);
        });
        JSONObject pack = new JSONObject();
        pack.put("规格与包装", detail);
        return pack;
    }


}


